package weaver.interfaces.qz.job;

import com.engine.qz.service.impl.MeritsServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/8/4
 * @Description 绩效系数排名计算
 * @Author AdminZm
 */
public class JxxsRankCountJob extends BaseCronJob {

    BaseBean baseBean = new BaseBean();

    @Override
    public void execute() {
        baseBean.writeLog("JxxsRankCountJob start.");
        int dayOfMonth = LocalDate.now().getDayOfMonth();
        YearMonth ny = YearMonth.now();
        YearMonth sy = ny.minusMonths(1);
        int lastDay = ny.lengthOfMonth();
        String endDate = ny + "-" + lastDay;
        String startDate = ny + "-01";
        if (dayOfMonth <= 5) {
            startDate = sy + "-01";
        }
        RecordSet rs = new RecordSet();
        // 排名绩效系数计算方案
        Set<String> faIdSet = new HashSet<>();
        rs.execute("SELECT id FROM uf_jxxsjsfa");
        while (rs.next()) {
            String id = rs.getString("id");
            if (StringUtils.isEmpty(id)) {
                continue;
            }
            faIdSet.add(id);
        }
        if (CollectionUtils.isEmpty(faIdSet)) {
            baseBean.writeLog("JxxsRankCountJob faIdSet is null.");
            return;
        }

        MeritsServiceImpl meritsServiceImpl = new MeritsServiceImpl();
        Map<String, Object> params = new HashMap<>();

        String sql = "SELECT id FROM uf_khjhdy WHERE szlx = 0 AND jhksrq <= '" + endDate + "' AND jhjsrq >= '" + startDate + "'";
        rs.execute(sql);
        while (rs.next()) {
            String id = rs.getString("id");
            if (StringUtils.isEmpty(id)) {
                continue;
            }
            for (String faId : faIdSet) {
                try {
                    params = new HashMap<>();
                    params.put("khjh", id);
                    params.put("qzfbfa", faId);
                    Map<String, Object> map = meritsServiceImpl.jxxsRankCount(params);
                    baseBean.writeLog("JxxsRankCountJob dt result:" + id + "、" + faId + "、" + map);
                } catch (Exception e) {
                    baseBean.writeLog("JxxsRankCountJob dt error:" + id + "、" + faId + "、" + e);
                }
            }
        }
        baseBean.writeLog("JxxsRankCountJob end.");
    }
}
